import React, { useEffect, useState } from 'react';
import { Avatar, Dropdown, MenuProps, DropdownProps, App } from 'antd';
import { useTranslation } from 'react-i18next';
import { useThemeToken } from '@/theme/hooks';
import { useUserInfo, useUserActions } from '@/store/userStore';
import { useRouter } from '@/router/hooks';
import usePermission from '@/hooks/event/usePermission';
import { useInitializeData } from '@/store/configStore';
import DeleteConfirmModal from '@/pages/datasets/components/DeleteConfirmModal';
import AdviceModal from '@/pages/components/modal/AdviceModal';
import LicenseConfirmModal from '@/pages/components/modal/LicenseConfirm';
import LicenseModal from '@/pages/components/modal/LicenseModal';
import ResetPasswordModal from '@/pages/components/modal/ResetPasswordModal';
import { logout } from '@/pages/auth/authUtils';
import appService from '@/api/services/appService';
import { SvgIcon } from '../icon';
import ImageDisplay from '@/components/work-modal/components/ImageDisplay';

interface UserDropdownMenuProps {
  username?: string;
  avatar?: string;
  menuItems?: MenuProps['items'];
  onChangeInfo?: () => void;
  onLicense?: () => void;
  onShowKeyHistory?: () => void;
  showKeyHistoryBtn?: boolean;
  showHomeBtn?: boolean;
  showLicenseBtn?: boolean;
  showFeedbackBtn?: boolean;
  showChangeInfoBtn?: boolean;
  showLogoutBtn?: boolean;
  // 控制弹窗外部可控
  adviceModalProps?: Partial<React.ComponentProps<typeof AdviceModal>>;
  deleteConfirmModalProps?: Partial<React.ComponentProps<typeof DeleteConfirmModal>>;
  licenseConfirmModalProps?: Partial<React.ComponentProps<typeof LicenseConfirmModal>>;
  licenseModalProps?: Partial<React.ComponentProps<typeof LicenseModal>>;
  resetPasswordModalProps?: Partial<React.ComponentProps<typeof ResetPasswordModal>>;
}

const UserDropdownMenu: React.FC<UserDropdownMenuProps> = ({
  username: propUsername,
  avatar: propAvatar,
  menuItems,
  onChangeInfo,
  onLicense,
  showHomeBtn = true,
  showLicenseBtn = true,
  showFeedbackBtn = true,
  showChangeInfoBtn = true,
  showLogoutBtn = true,
  adviceModalProps = {},
  deleteConfirmModalProps = {},
  licenseConfirmModalProps = {},
  licenseModalProps = {},
  resetPasswordModalProps = {},
}) => {
  const { message } = App.useApp();
  const { t } = useTranslation();
  const { colorBgElevated, boxShadowSecondary, colorPrimary } = useThemeToken();
  const { isAdmin, isSuperAdmin } = usePermission();
  const initializeData = useInitializeData();
  const router = useRouter();
  const userInfo = useUserInfo();
  const username = propUsername || userInfo.username;
  const isRoot = username === 'root';

  // 弹窗状态
  const [logoutVisible, setLogoutVisible] = useState(false);
  const [passwordModalVisible, setPasswordModalVisible] = useState(false);
  const [isLicenseModalOpen, setIsLicenseModalOpen] = useState(false);
  const [isActivateConfirmModalOpen, setIsActivateConfirmModalOpen] = useState(false);
  const [inputValue, setInputValue] = useState('');
  const [actIcon, setActIcon] = useState<number>(0);
  const [showAdvice, setShowAdvice] = useState(false);
  const [dropdownOpen, setDropdownOpen] = useState(false);
  const [modalOpen, setModalOpen] = useState(false);

  // 监听所有模态框状态变化
  useEffect(() => {
    const isAnyModalOpen =
      logoutVisible ||
      passwordModalVisible ||
      isLicenseModalOpen ||
      isActivateConfirmModalOpen ||
      showAdvice;
    setModalOpen(isAnyModalOpen);
  }, [
    logoutVisible,
    passwordModalVisible,
    isLicenseModalOpen,
    isActivateConfirmModalOpen,
    showAdvice,
  ]);

  // 默认菜单项
  const defaultItems: MenuProps['items'] = [
    // ...(showHomeBtn && (isAdmin || isSuperAdmin || initializeData.is_knowledge_manager || initializeData.is_knowledge_reviewer)
    //   ? [{
    //     key: '0',
    //     label: <button className="text-center">{t('page.homePage.backWorkspace')}</button>,
    //     style: { padding: '10px' },
    //     onClick: () => router.push('/worklayouts/'),
    //   }]
    //   : []),
    // ...(showChangeInfoBtn ? [{
    //   key: '1',
    //   label: <button className="text-center">{t('page.homePage.changeInformation')}</button>,
    //   style: { padding: '10px' },
    //   onClick: () => {
    //     setPasswordModalVisible(true);
    //     setDropdownOpen(false);
    //     onChangeInfo?.();
    //   },
    // }] : []),
    ...(showFeedbackBtn
      ? [
        {
          key: '2',
          label: <button className="text-center ">{t('page.homePage.userFeedback')}</button>,
          style: { padding: '10px' },
          onClick: () => {
            if (showLicenseBtn && !initializeData?.is_license_valid) {
              setIsActivateConfirmModalOpen(true);
            } else {
              setInputValue('');
              setActIcon(0);
              setShowAdvice(true);
            }
            setDropdownOpen(false);
          },
        },
      ]
      : []),
    ...(showLicenseBtn && isRoot
      ? [
        {
          key: '3',
          label: <button className="text-center ">{t('page.homePage.license')}</button>,
          style: { padding: '10px' },
          onClick: () => {
            setIsLicenseModalOpen(true);
            setDropdownOpen(false);
            onLicense?.();
          },
        },
      ]
      : []),
    ...(showLogoutBtn
      ? [
        {
          key: '5',
          label: <button className="text-center ">{t('page.homePage.logOut')}</button>,
          style: { padding: '10px', color: 'red' },
          onClick: () => {
            setLogoutVisible(true);
            setDropdownOpen(false);
          },
        },
      ]
      : []),
  ];

  const items = menuItems || defaultItems;

  const contentStyle: React.CSSProperties = {
    backgroundColor: colorBgElevated,
    borderRadius: '10px',
    boxShadow: boxShadowSecondary,
    width: '120px',
  };
  const menuStyle: React.CSSProperties = {
    boxShadow: 'none',
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
  };
  const dropdownRender: DropdownProps['dropdownRender'] = (menu) => (
    <div style={contentStyle}>
      {React.cloneElement(menu as React.ReactElement, { style: menuStyle })}
    </div>
  );
  const handleDropdownVisibleChange = (flag: boolean) => {
    if (modalOpen && flag) return;
    setDropdownOpen(flag);
  };

  const handleAdviceConfirm = async (actId: number, text: string) => {
    appService
      .surveySubmit({
        content: {
          title: t('page.homePage.postTitleText'),
          feedback: text,
          score: actId,
        },
      })
      .then((res) => {
        console.log(res);
        message.success(t('page.homePage.submitSuccess'));
        setActIcon(0);
        setInputValue('');
        setShowAdvice(false);
      });
  };

  return (
    <Dropdown
      menu={{ items }}
      placement={'bottomLeft'}
      trigger={['hover', 'click']}
      dropdownRender={dropdownRender}
      open={dropdownOpen}
      onOpenChange={handleDropdownVisibleChange}
      disabled={modalOpen}
    >
      <div className="flex cursor-pointer items-center">
        {/* <Avatar
          className="h-10 w-10 transform-none cursor-pointer px-0 hover:scale-105"
          style={{ backgroundColor: colorPrimary }}
        >
          {username && username[0]}
        </Avatar> */}
        {userInfo?.avatar ? (
          <ImageDisplay
            src={userInfo?.avatar || ''}
            alt="avatar"
            containerClassName='rounded-[50%] w-[35px] h-[35px] border-none'
          />
        ) : (
          <SvgIcon icon="ic-avatar" size="35" className="mr-2 rounded-md" />
        )}
        <DeleteConfirmModal
          visible={logoutVisible}
          text="确定要退出登录吗?"
          onCancel={() => setLogoutVisible(false)}
          onConfirm={() => {
            setLogoutVisible(false);
            logout();
          }}
          onConfirmText="退出登录"
          {...deleteConfirmModalProps}
        />
        <AdviceModal
          visible={showAdvice}
          actIcon={actIcon}
          setActIcon={setActIcon}
          inputValue={inputValue}
          setInputValue={setInputValue}
          onCancel={() => setShowAdvice(false)}
          onConfirm={handleAdviceConfirm}
          {...adviceModalProps}
        />
        <LicenseConfirmModal
          visible={isActivateConfirmModalOpen}
          onCancel={() => setIsActivateConfirmModalOpen(false)}
          {...licenseConfirmModalProps}
        />
        <LicenseModal
          visible={isLicenseModalOpen}
          onCancel={() => setIsLicenseModalOpen(false)}
          {...licenseModalProps}
        />
        <ResetPasswordModal
          visible={passwordModalVisible}
          onCancel={() => setPasswordModalVisible(false)}
          {...resetPasswordModalProps}
        />
      </div>
    </Dropdown>
  );
};

export default UserDropdownMenu;
